<?php
$loader->requireOnce('includes/Utils.class.php');
class C_PaymentCommon extends Controller {
    private $logger;
    function __construct($template_mod = "general") {
        parent::Controller();
        $this->template_mod = $template_mod;
        $this->logger = LoggerManager::getLogger('module.billing.controllers.C_PaymentCommon');
        $this->view->path   =   "payment_common";
    }

     public function actionGetTicketCommonAjax($ticketId) {
    	$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
    	if (isset($_GET['ticketId'])) {
    		$ticketId	=	$_GET['ticketId'];
    	}
    	$this->logger->info("Start action GetTicketCommonAjax {ticketId='$ticketId'}");
		$objTicket	=	Celini::newORDO('Ticket', $ticketId);
		$patientId	=	$objTicket->getPatientId();
		$examinationType	=	$objTicket->get('enum_examination_type');
		$insInfoList		=	PaymentProcessor::getInsuranceInfoObjects($ticketId);
		$this->assign('examinationTypeList', Utils::getEnumArrayKey(EnumerationConstant::EXAMINATION_TYPE));
        $this->assign('enumExaminationType', $examinationType);
        $this->assign('examinationType', Utils::getEnumTextByKey(EnumerationConstant::EXAMINATION_TYPE, $examinationType));
        $this->assign('insuranceType', Utils::getEnumKey(EnumerationConstant::EXAMINATION_TYPE, EnumerationConstant::EXAMINATION_TYPE_INSURANCE));
        $this->assign('insInfoList', $insInfoList);
        $this->assign('ticketId', $ticketId);

        $cardList	=	Celini::newORDO('Insurance')->getAvailableInsuranceByPatient($patientId);
		$this->assign('insuranceCardList', $cardList);
		$this->assign('patientId', $patientId);
		$this->assign('patientName', Celini::newORDO('Person', $patientId)->getName());
		//@LOCALIZATION
        $orders =   L10nHelper::getYMDorder();
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
        $result['result']	=	$this->view->render('ticket_common.html');
        $this->logger->info("End action GetTicketCommonAjax {ticketId='$ticketId'}");

        return json_encode($result);
	}

	public function actionUpdateTicketCommonAjax() {
		$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $ticketId           =   $_POST['ticketId'];
        $examType           =   $_POST['examinationType'];
        $discountProgram    =   $_POST['discountProgram'];
        $objTicket  =   Celini::newORDO('Ticket', $ticketId);
        $objTicket->populateArray(array(
            'enum_examination_type' =>  $examType,
            'sale_program_store_id' =>  $discountProgram
        ));
        // Update ticket
        $objTicket->persist();

        // Update ticket_insurance
        Celini::newORDO('TicketInsurance')->deleteByTicket($ticketId);
        if ($examType == Utils::getEnumKey(EnumerationConstant::EXAMINATION_TYPE, EnumerationConstant::EXAMINATION_TYPE_INSURANCE)){
	        for ($i =   0; $i < $_POST['cardNumber']; $i++) {
	        	$objTicketIns   =   Celini::newORDO('TicketInsurance');
	        	$insId    =   $_POST["insuranceCard_$i"]['insuranceId'];
	        	$route    =   0;
	        	if ($_POST["insuranceCard_$i"]['correctRoute'] === 'true') {
	        		$route   =   1;
	        	}
	        	$paid =   0;
	        	if ($_POST["insuranceCard_$i"]['paidFor36Months'] === 'true') {
                    $paid     =   1;
	        	}
	        	$objTicketIns->setData($ticketId, $insId, $route, $paid);
                $objTicketIns->persist();
	        }
        }
        return json_encode($result);
	}

	public function actionGetCollectionReceiptsAjax($ticketId = 0, $jsAction, $dialogId){
		$result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        if (isset($_GET['ticketId'])) {
        	$ticketId	=	$_GET['ticketId'];
        }
        if (isset($_GET['jsAction'])) {
        	$jsAction	=	Utils::sanitizeText($_GET['jsAction']);
        }
        if (isset($_GET['dialogId'])) {
        	$dialogId	=	Utils::sanitizeText($_GET['dialogId']);
        }
        $objTicket		=	Celini::newORDO('Ticket', $ticketId);
        $paymentInfo	=	Celini::newORDO('PayReceipt')->getPaymentInfoByTicket($ticketId,
        	EnumerationConstant::PAYMENT_COLLECTION_TYPE_COLLECTING_KEY);
        $this->assign('paymentInfo', $paymentInfo);
        $this->assign('index', 1);
        $this->assign('jsAction', $jsAction);
        $this->assign('dialogId', $dialogId);

        $result['result']['html']		=	$this->view->render('view_collecting_receipt.html');
        $result['result']['ticketName']	=	$objTicket->get('name');

        return json_encode($result);
	}

    /**
     * View all payment receipts of a ticket.
     *
     * @param int $ticketId Ticket Id
     * @return json Result object
     */
	public function actionViewAdvancePaymentDetails($ticketId = '') {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        if (isset($_POST['ticketId'])) {
            $ticketId   =   $_POST['ticketId'];
        }
        if (isset($_POST['notShowTotal'])) {
            $notShowTotal   =   1;
        }
        $this->logger->info("Start action ViewAdvancePaymentDetails {ticketId='$ticketId'}");
        $paymentInfo    =   Celini::newORDO('PayReceipt')->getPaymentInfoByTicket($ticketId);
        $total          =   0;
        foreach ($paymentInfo as &$item) {
            $total         +=   $item['amount'];
            if ($item['amount'] < 0) {
                $item['color'] =   'red';
                $item['amount'] = - $item['amount'];
            }
        }
        $result['result']['ticketName'] =   Celini::newORDO('Ticket', $ticketId)->getName();
        $this->assign('paymentInfo', $paymentInfo);
        $this->assign('total', L10nHelper::renderNumber($total));
        $this->assign('index', 1);
        $this->assign('paybackId', EnumerationConstant::PAYMENT_COLLECTION_TYPE_PAYBACK_KEY);
        $this->assign('notShowTotal', $notShowTotal);
        $result['result']['html']  = $this->view->render('view_advance_payment_detail.html');
        $this->logger->info("End action ViewAdvancePaymentDetails {ticketId='$ticketId'}");
        return json_encode($result);
    }
    
    /**
     * Render ticket list. It is used in search patient functions.
     *
     * @param array $ticketList Ticket list
     * @param string $jsFucntion Javascript function name to assign to click actions
     * @param string $dialogId Id of container to show ticket list result
     * @param string $ticketListTitle  Title of table showing tickets
     * @return string Html result
     */
    public function renderTicketList($ticketList, $jsFunction, $dialogId = '', $ticketListTitle='') {
    	$this->assign('ticketList', $ticketList);
    	$this->assign('jsFunction', $jsFunction);
    	$this->assign('dialogId', $dialogId);
    	$this->assign('ticketListTitle', $ticketListTitle);
    	$this->assign('index', 1);

		return $this->view->render('ticket_list.html');
    }
    
    public function renderTicketListOption($ticketList, $ticketId) {
        // Build today ticket list and closed ticket list
        $today  =   date('Y-m-d');
        $closedTicketList   =   array();
        foreach ($ticketList as $key => $ticket) {
            if (strtotime($ticket['created']) >= strtotime($today)) {
                continue;
            }
            else {
                $closedTicketList[] =   $ticket;
                unset($ticketList[$key]);
            }
        }
        $this->assign('openTicketList', $ticketList);
        $this->assign('closedTicketList', $closedTicketList);
        $this->assign('ticketId', $ticketId);
        
        return $this->view->render('ticket_list_option.html');
    }
}
?>